<template>
    <div :style="conheight" @contextmenu="showMenu">
        <grid-layout
                :layout.sync="layout"
                :col-num="12"
                :row-height="rowHeight"
                :is-draggable="!isLock"
                :is-resizable="!isLock"
                :responsive="true"
                :useStyleCursor="!isLock"
                :vertical-compact="true"
                :preventCollision="false"
                @layout-updated="layoutUpdatedEvent"
                @layout-ready="layoutReadyEvent"
        >
            <grid-item
                    v-for="(item,index) in layout"
                    :x="item.x"
                    :y="item.y"
                    :w="item.w"
                    :h="item.h"
                    :i="item.i"
                    :minW="item.minW"
                    :minH="item.minH"
                    :key="item.i"
                    @resize="resizeEvent"
                    @move="moveEvent"
                    @resized="resizedEvent"
                    @moved="movedEvent"
            >
                <component  @homeComponentDelete="homeComponentDelete" :isLock="!isLock"  :homeIndex="index"
                            :divHeight="(item.h-1)*(rowHeight+10)+rowHeight" ref="layout" :is="item.component"></component>

            </grid-item>
        </grid-layout>
        <vue-context-menu :contextMenuData="contextMenuData" @addComponentMenu="addComponentMenu" @unlockPage="unlockPage"
                          @toDefault="toDefault"  @lockPage="lockPage"></vue-context-menu>
        <component-selector ref="componentSelectorRef" @addComponent="addComponent"></component-selector>
    </div>
</template>

<script>
    import {Api} from '../../../api/index.js';
    import {sessionStorage} from '@/common/cacheUtils.js';
    import VueGridLayout from 'vue-grid-layout';
    import ComponentSelector from './homeComponents/componentSelect.vue'
    import jrdb from './homeComponents/jrdb.vue';
    import fengxiandengji from './homeComponents/fengxiandengji.vue';
    import sjtj from './homeComponents/sjtj.vue';
    import taizhang from './homeComponents/taizhang.vue';
    import xiangguanlianjie from './homeComponents/xiangguanlianjie.vue';
    import yinhuan from './homeComponents/yinhuan.vue';
    import zyxk from './homeComponents/zyxk';
    import kjcd from './homeComponents/kjcd.vue';
    import remenhuodong from './homeComponents/remenhuodong';
    import falvfagui from './homeComponents/falvfagui';
    import tongzhigonggao from './homeComponents/tongzhigonggao';
    import kepuxuanjiao from './homeComponents/kepuxuanjiao';

    export default {
        name: "homepage",
        components: {
            GridLayout: VueGridLayout.GridLayout,
            GridItem: VueGridLayout.GridItem,
            ComponentSelector,
            jrdb,
            fengxiandengji,
            sjtj,
            taizhang,
            xiangguanlianjie,
            yinhuan,
            kjcd,
            zyxk,
            remenhuodong,
            falvfagui,
            tongzhigonggao,
            kepuxuanjiao
        },
        data() {
            return {
                homePageInfo:{},
                defaultLayout:{},
                conheight:{
                    height:'',
                    backgroundColor:'#F5F7F9',
                    paddingRight:'20px',
                    overflowY:'auto'
                },
                marginArr:[10,10],
                rowHeight:30,
                isLock:true,
                layoutMap: [],
                layoutColNum:12,
                layout:[],
                defaultLayout: [
                    {
                        i:0,
                        x:0,
                        y:0,
                        w:3,
                        h:8,
                        minH:8,
                        minW:3,
                        component:'zyxk'
                    },
                    {
                        i:31,
                        x:9,
                        y:2,
                        w:3,
                        h:6,
                        minW:2,
                        minH:6,
                        component:'kjcd'
                    },
                    {
                        i:2,
                        x:3,
                        y:0,
                        w:6,
                        h:8,
                        minW:6,
                        minH:8,
                        component:'sjtj'
                    },
                    {
                        i:3,
                        x:9,
                        y:0,
                        w:3,
                        h:2,
                        minW:3,
                        minH:2,
                        component:'jrdb'
                    },
                    {
                        i:4,
                        x:0,
                        y:8,
                        w:4,
                        h:8,
                        minW:2,
                        minH:4,
                        component:'yinhuan'
                    },
                    {
                        i:5,
                        x:8,
                        y:8,
                        w:4,
                        h:8,
                        minW:2,
                        minH:4,
                        component:'fengxiandengji'
                    },
                    {
                        i:6,
                        x:4,
                        y:8,
                        w:4,
                        h:7,
                        minW:4,
                        minH:7,
                        component:'taizhang'
                    },
                    {
                        i:7,
                        x:0,
                        y:15,
                        w:12,
                        h:4,
                        minW:12,
                        minH:4,
                        component:'xiangguanlianjie'
                    },
                    {
                        i:8,
                        x:0,
                        y:19,
                        w:12,
                        h:7,
                        minW:12,
                        minH:7,
                        component:'remenhuodong'
                    },
                    {
                        i:9,
                        x:0,
                        y:26,
                        w:4,
                        h:8,
                        minW:4,
                        minH:7,
                        component:'falvfagui'
                    },
                    {
                        i:10,
                        x:4,
                        y:26,
                        w:4,
                        h:8,
                        minW:4,
                        minH:7,
                        component:'kepuxuanjiao'
                    },
                    {
                        i:11,
                        x:8,
                        y:26,
                        w:4,
                        h:8,
                        minW:4,
                        minH:7,
                        component:'tongzhigonggao'
                    },
                ],
                contextMenuData: {
                    menuName: "菜单",
                    axis: {
                        x: null,
                        y: null
                    },
                    menulists: [
                        {
                            fnHandler: "unlockPage",
                            btnName: "解锁"
                        },
                    ]
                }
            }
        },
        computed: {

        },
        mounted() {
            this.conheight.height=window.innerHeight-80+'px';
            this.$http.get(Api.HomePageConfig + "/" +sessionStorage('userId').getObject('userId').companyId +
                "/" + sessionStorage('userId').getObject('userId').userId).then((res) => {
                this.homePageInfo = res.data.data;
                this.layout = res.data.data == null ?[] :res.data.data.content ==null?[]:JSON.parse(res.data.data.content);
            }).catch(e => {
                this.$Message.error("获取首页配置失败")
            })
        },
        methods: {
            layoutReadyEvent(newLayout) {

            },
            layoutUpdatedEvent(newLayout) {

            },
            homeComponentDelete(index){
                this.layout.splice(index,1);
            },
            moveEvent: function(i, newX, newY){
                console.log("MOVE i=" + i + ", X=" + newX + ", Y=" + newY);
            },
            resizeEvent: function(i, newH, newW, newHPx, newWPx){
            },
            movedEvent: function(i, newX, newY){
            },
            resizedEvent: function(i, newH, newW, newHPx, newWPx){
                for(let x = 0;x<this.layout.length;x++){
                    if(this.layout[x].i == i){
                        this.$refs.layout[x].resize();
                        break;
                    }
                }
            },
            addComponent(component) {
                var itemId = 0;
                let itemIds = [];

                for (let x = 0; x < this.layout.length; x++) {
                    itemIds.push(this.layout[x].i)
                }
                console.log(itemIds);
                for (var i = 0; i < itemIds.length + 100; i++){
                    if (itemIds.indexOf(i) < 0) {
                        itemId = i;
                        break;
                    }
                }
                component.i = itemId;
                // 确定边界
                let Ys = [], maxX = 0, maxY = 0, edgeX = 0, edgeY = 0
                this.layout.map(item => {
                    Ys.push(item.y + item.h)
                })
                maxY = Ys.length && Math.max.apply(null, Ys) || 1
                edgeX = 12
                edgeY = maxY
                // 使用二维数组生成地图
                let gridMap = new Array()
                for (let x = 0; x < edgeX; x++) {
                    gridMap[x] = new Array()
                    for (let y = 0; y < edgeY; y++) {
                        gridMap[x][y] = 0
                    }
                }
                // 标记占位
                this.layout.map(item => {
                    // 将layout中卡片所占区域标记为1
                    for (let x = item.x; x < (item.x + item.w); x++) {
                        for (let y = item.y; y < (item.y + item.h); y++) {
                            gridMap[x][y] = 1
                        }
                    }
                })
                // 遍历地图，申请位置
                for (let y = 0; y < edgeY; y++) {
                    for (let x = 0; x < edgeX; x++) {
                        // 申请所需空间
                        if (edgeX - x >= component.w && edgeY - y >= component.h) {
                            let itemSignArr = []
                            for (let a = x; a < (x + component.w); a++) {
                                for (let b = y; b < (y + component.h); b++) {
                                    itemSignArr.push(gridMap[a][b])
                                }
                            }
                            if (itemSignArr.indexOf(1) < 0) {
                                component.x = x
                                component.y = y
                                this.$refs.componentSelectorRef.visible = false;
                                component.move = true;
                                this.layout.push(component)
                                return
                            }
                        }
                    }
                }
                // 无满足条件
                component.x = 0
                component.y = edgeY + 1
                this.layout.push(component)
                this.$refs.componentSelectorRef.visible = false;
            },
            showMenu() {
                event.preventDefault();
                var x = event.clientX;
                var y = event.clientY;
                // Get the current location
                this.contextMenuData.axis = {
                    x,
                    y
                };
            },
            addComponentMenu() {
                this.$refs.componentSelectorRef.visible = true;
            },
            unlockPage() {
                this.defaultLayout = this.copyArr(this.layout);
                this.isLock = false;
                this.contextMenuData.menulists = [
                    {
                        fnHandler: "lockPage", // Binding events(绑定事件)
                        icoName:"md-add-circle",
                        btnName: "锁定" // The name of the menu option (菜单名称)
                    },
                    {
                        fnHandler: "addComponentMenu", // Binding events(绑定事件)
                        icoName:"md-add-circle",
                        btnName: "添加组件" // The name of the menu option (菜单名称)
                    },
                    {
                        fnHandler: "toDefault", // Binding events(绑定事件)
                        icoName:"md-add-circle",
                        btnName: "恢复默认" // The name of the menu option (菜单名称)
                    }
                ];
            },
            lockPage() {
                this.isLock = true;
                this.contextMenuData.menulists = [
                    {
                        fnHandler: "unlockPage", // Binding events(绑定事件)
                        icoName:"md-add-circle",
                        btnName: "解锁" // The name of the menu option (菜单名称)
                    }
                ]
                var data={
                    userId: sessionStorage('userId').getObject('userId').userId,
                    companyId: sessionStorage('userId').getObject('userId').companyId,
                    content: JSON.stringify(this.layout)
                }
                if(this.homePageInfo != {} && this.homePageInfo.userId == sessionStorage('userId').getObject('userId').userId){
                    data.id = this.homePageInfo.id;
                }
                this.$http.post(Api.HomePageConfig,data).then((res) => {
                }).catch(e => {
                    this.$Message.error("首页配置保存失败")
                })
            },
            toDefault(){
                this.layout= this.copyArr(this.defaultLayout);
            },
            copyArr(obj) {
                const isObject = args => (typeof args === 'object' || typeof args === 'function')
                if (!isObject) throw new Error('Not Reference Types')
                const newObj = Array.isArray(obj) ? [...obj] : { ...obj }
                Reflect.ownKeys(newObj).map(key => {
                    newObj[key] = isObject(obj[key]) ? this.copyArr(obj[key]) : obj[key]
                })
                return newObj
            },
        }

    }
</script>
<style>

    .vue-grid-item > .vue-resizable-handle {
        width: 24px !important;
        height: 24px !important;
        background: url('')
        0 0/24px 24px !important;
        padding: 0 !important;
        transform: rotate(135deg) !important;
    }



    .context-menu-list:hover {
        background: #F27874 !important;
    }

    .btn-wrapper-simple{
        position: relative !important;
        height: 25px !important;
        line-height: 25px !important;
    }

    .nav-name-right {
        margin: 0 20px !important;
        height: 25px !important;
        line-height: 25px !important;
        display: block !important;
    }
</style>